package com.yxx.community.controller;

import com.yxx.community.dto.AccessTokenDTO;
import com.yxx.community.dto.GiteeUser;
import com.yxx.community.mapper.UserMapper;
import com.yxx.community.model.User;
import com.yxx.community.provider.GithubProvider;
import com.yxx.community.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * @Author: YuXinXin
 * @Description:
 * @Date:Created in 15:42 2020/1/25
 **/
@Controller
@Configuration
public class AuthorizeController {

  @Autowired
  private GithubProvider githubProvider;

  @Autowired
  private UserService userService;

  @Value("${gitee.Grant_type}")
  private String Grant_type;
  @Value("${gitee.Client_id}")
  private String Client_id;
  @Value("${gitee.Redirect_uri}")
  private String Redirect_uri;
  @Value("${gitee.Client_secret}")
  private String Client_secret;

  @Autowired
  private UserMapper userMapper;

  @GetMapping("/callback")
  public String callback(@RequestParam("code") String code,
                         HttpServletResponse response){
    AccessTokenDTO accessTokenDTO = new AccessTokenDTO();
    accessTokenDTO.setGrant_type(Grant_type);
    accessTokenDTO.setCode(code);
    accessTokenDTO.setClient_id(Client_id);
    accessTokenDTO.setRedirect_uri(Redirect_uri);
    accessTokenDTO.setClient_secret(Client_secret);
    String accessToken = githubProvider.getAccessToken(accessTokenDTO);
    GiteeUser giteeUser = githubProvider.getUser(accessToken);
    if(giteeUser!=null)
    {
      User user = new User();
      String token = UUID.randomUUID().toString();
      user.setToken(token);
      user.setName(giteeUser.getName());
      user.setAccountId(String.valueOf(giteeUser.getId()));
      user.setAvatarUrl(giteeUser.getAvatarUrl());
      userService.createOrUpdate(user);
      response.addCookie(new Cookie("token",token));
      return "redirect:/";
    }else{
      //登录失败
      return "redirect:/";
    }
  }

  @GetMapping("/logout")
  public String logout(HttpSession session,
                       HttpServletResponse response){
    session.removeAttribute("user");
    Cookie cookie = new Cookie("token",null);
    cookie.setMaxAge(0);
    response.addCookie(cookie);
    return "redirect:/";
  }
}
